//
//  WBHTTPClient.swift
//  WeiBo
//
//  Created by chenguanglei on 16/11/27.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPType: String {
    
    case post = "POST"
    case get = "GET"
    case head = "HEAD"
}

class WBHTTPClient: AFHTTPSessionManager {
    
    
    static let shareInstance : WBHTTPClient = {
        
        let url = URL(string: "https://api.weibo.com/")
        
        let client = WBHTTPClient(baseURL: url)
        
        client.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return client
    }()
    
    
    
    
    func request(type: HTTPType,_ URLString: String, parameters: Any?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil){
        
        
        if type == .get {
            
            self.get(URLString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
        }else if type == .post {
            
            self.post(URLString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
            
        }
        
    }
    
    
    
    func request(type: HTTPType,_ URLString: String, parameters: Any?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil){
        
        request(type: type, URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        
    }
    
    
    
    func request(type: HTTPType,_ URLString: String, parameters: Any?, success: ((Any?) -> Void)?, failure: ((Error) -> Void)? = nil){
        
        
        let successBlock = {(task:URLSessionDataTask, json:Any?) in
            
            guard let json = json as? [String:Any] else {
                return
            }
            
            success!(json)
            
        }
        
        
        let failureBlock = {(task:URLSessionDataTask?, error:Error) in
        
            failure!(error)
        
        }
        
        
        request(type: type, URLString, parameters: parameters, success: successBlock, failure: failureBlock)
        
    }
    
    
    class func request(type: HTTPType,_ URLString: String, parameters: Any?, success: ((Any?) -> Void)?, failure: ((Error) -> Void)? = nil){
    
        WBHTTPClient.shareInstance.request(type: type, URLString, parameters: parameters, success: success, failure: failure)
    }
}
    

